import React, { useCallback, useEffect, useState } from 'react'
import { Input } from 'antd'
import { CloseOutlined, SettingOutlined } from '@ant-design/icons'
import useSearch from '../../hooks/useSearch'
import { useThemeStore, useEngineStore } from '@renderer/stores'
import SuggestionList from './components/SuggestionList'
import Moon from '../../icon/Moon'
import Sun from '../../icon/Sun'
import SettingPanel from './components/SettingPanel'

const SearchInstance: React.FC = () => {
  const { isDark } = useThemeStore()
  const { engine } = useEngineStore()
  const { getSuggestions, handleStartSearch, searchConfig } = useSearch()
  const [schema, setSchema] = useState<string>('')
  const [intellisenseList, setIntellisenseList] = useState<string[]>([])
  const [selectedIndex, setSelectedIndex] = useState<number>(-1)
  const [showSettingPanel, setShowSettingPanel] = useState<boolean>(false)

  const handleSearch = (newSchema?: string) => {
    handleClear()
    handleStartSearch(newSchema || schema)
  }

  const handleClear = () => {
    setSelectedIndex(-1)
    setIntellisenseList([])
  }

  const handleInput = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>) => {
      const value = e.target.value
      getSuggestions(value).then((data) => {
        const match = data.match(/s:(\[[^\]]*\])/)
        setIntellisenseList(match ? JSON.parse(match[1]) : [])
      })
    },
    [getSuggestions]
  )

  const handleKeyDown = useCallback(
    (e: React.KeyboardEvent<HTMLInputElement>) => {
      if (intellisenseList.length === 0) return
      if (e.key === 'ArrowDown') {
        e.preventDefault()
        //如果已经是最后一个了 就不用了
        if (selectedIndex === intellisenseList.length - 1) return
        setSelectedIndex((prevIndex) => Math.min(prevIndex + 1, intellisenseList.length - 1))
        setSchema(intellisenseList[1 + selectedIndex!])
      } else if (e.key === 'ArrowUp') {
        e.preventDefault()
        //如果已经是第一个了 就不用了
        if (selectedIndex === 0 || selectedIndex === -1) return
        setSelectedIndex((prevIndex) => Math.max(prevIndex - 1, 0))
        setSchema(intellisenseList[-1 + selectedIndex!])
      }
    },
    [intellisenseList, selectedIndex, handleSearch]
  )

  const handleClickIntell = (intellisense: string) => {
    setSchema(intellisense)
    handleClear()
    handleSearch(intellisense)
  }

  useEffect(() => {
    const newHeight = showSettingPanel
      ? 52 + 120
      : intellisenseList.length > 0
        ? 52 + 36 * intellisenseList.length
        : 52

    window.electron.ipcRenderer.send('setSizeRange', newHeight, newHeight)
    window.electron.ipcRenderer.send('resize', 350, newHeight)
  }, [intellisenseList, showSettingPanel])
  return (
    <div className="overflow-x-hidden h-screen bg-white rounded-xl border box-border">
      <div
        className={[
          `on-draggle h-full  w-screen flex justify-center items-center`,
          `${isDark ? 'bg-[#141414]' : ''}`,
          `${intellisenseList.length > 0 || showSettingPanel ? 'border-b' : ''}`,
          `${intellisenseList.length > 0 || showSettingPanel ? 'max-h-[50px]' : ''}`
        ].join(' ')}
      >
        <div className="h-full p-2 w-[48px] flex justify-center items-center">
          {React.cloneElement(searchConfig[engine].icon, {
            style: { fontSize: '24px', color: isDark ? 'white' : 'black' }
          })}
        </div>
        <div className="off-draggle h-full w-full flex justify-center items-center">
          <Input
            variant="filled"
            onKeyDown={handleKeyDown}
            onInput={handleInput}
            allowClear
            onClear={handleClear}
            value={schema}
            onChange={(e: React.ChangeEvent<HTMLInputElement>) => setSchema(e.target.value)}
            onPressEnter={() => handleSearch()}
            placeholder="请输入搜索关键字"
          />
          {isDark ? <Sun /> : <Moon />}
          <SettingOutlined
            style={{ fontSize: '18px' }}
            className={`px-2 hover:text-blue-500 ${showSettingPanel ? 'text-blue-500' : isDark ? 'text-white' : 'text-black'}`}
            onClick={() => setShowSettingPanel((preval) => !preval)}
          />
          <CloseOutlined
            style={{ fontSize: '18px' }}
            className={`mr-2 off-draggle hover:text-red-600 ${isDark ? 'text-white' : 'text-black'}`}
            onClick={() => window.electron.ipcRenderer.send('close-all-processes')}
          />
        </div>
      </div>
      {!showSettingPanel && intellisenseList.length > 0 && (
        <SuggestionList
          intellisenseList={intellisenseList}
          selectedIndex={selectedIndex}
          handleClickIntell={handleClickIntell}
        />
      )}
      {showSettingPanel && (
        <SettingPanel handleCloseSettingPanel={() => setShowSettingPanel(false)} />
      )}
    </div>
  )
}

export default SearchInstance
